package com.cjb.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @Author chenjinbin
 * @Package IntelliJ IDEA
 * @Class ChangeTypeUtil
 * @Date 2023-09-27 22:50
 */

public class ChangeTypeUtil {
    /**
     * 日志
     */
    private final static Logger log = LoggerFactory.getLogger(ChangeTypeUtil.class);
    public static <T1, T2> T2 copyNonNullProperties(T1 source, T2 target) throws Throwable {
        Class<? extends T1> sourceClass = (Class<? extends T1>) source.getClass();
        Class<? extends T2> targetClass = (Class<? extends T2>) target.getClass();

        for (Field sourceField : sourceClass.getDeclaredFields()) {
            sourceField.setAccessible(true);
            if (!Modifier.isStatic(sourceField.getModifiers())) { // Only copy non-static fields
                if (sourceField.get(source) != null) {
                    try {
                        Field targetField = targetClass.getDeclaredField(sourceField.getName());
                        targetField.setAccessible(true);
                        targetField.set(target, sourceField.get(source));
                    } catch (NoSuchFieldException e) {
                        //log.info("复制异常,但是这个错误不需要被处理抛出就可以了 {}",JsonUtils.toJsonString(e));
                    }
                }
            }
        }
        return target;
    }
}
